module executor.rpc.server.RpcRequestExecutor;

import msgtrans;
import message.Constants;
import message.MsgDefine;
import google.protobuf;
import hunt.logging;
import hunt.util.Serialize;
import client.MsgServerClient;
import client.ImClient;
import client.LogicServerClient;
import std.array;
import std.conv : to;
import core.stdc.time;
import core.stdc.string;
import comm.comm;
import client.RpcRequestsMap;

@TransportServer(gateServerName)
class RpcRequestExecutor: AbstractExecutor!(RpcRequestExecutor) {

  @MessageId(MESSAGE.CMD_RPC_REQUEST)
  void rpcRequest(TransportContext ctx, MessageBuffer buffer) {
    auto req = new RPC_REQUEST();
    buffer.data.fromProtobuf!RPC_REQUEST(req);

    User u = cast(User)ctx.session.getAttribute(SESSIONKEY.USER);
    AuthenticateREQ authorize = cast(AuthenticateREQ)ctx.session.getAttribute(SESSIONKEY.SRC);

    ClientExtend clientExtend;
    memcpy(&clientExtend,buffer.extend.ptr,ClientExtend.sizeof);
    ServerExtend serverExtend;
    serverExtend.requestId = clientExtend.requestId;


    if(u !is null)
    {
       req.src = authorize.src;
       serverExtend.userId = to!ulong(u.id);
    }else
    {
        ErrorObj obj;
        obj.code = ErrorCode.ERR_NOT_LOGGED_IN;
        obj.message = "用户没有登录";
        ubyte[] extend = buffer.extend;
        RPC_RESPONSE res = new RPC_RESPONSE;
        res.content = EncodeJsonValue(obj);
        ctx.session.send(new MessageBuffer(MESSAGE.CMD_RPC_RESPONST,res.toProtobuf.array,extend));
        return;
    }

    MessageTransportClient client = LogicServerClient.getInstance.getForwardClient();

    ubyte[ServerExtend.sizeof] extend ;
    memcpy(extend.ptr,&serverExtend,ServerExtend.sizeof);


    client.send(new MessageBuffer(MESSAGE.CMD_RPC_REQUEST,req.toProtobuf.array,extend));
    RequestInfo info;
    info.userId = serverExtend.userId;
    info.requestId = serverExtend.requestId;
    info.src = req.src;
    RpcRequestsMap.getInstance().addRequest(info);
  }
}

